//自定义表单开始
$(document).ready(function () {
    //预览
    var chss = 0;
    $('.btn-yulan').click(function () {
        if (chss == 0) {
            $("#colzuo").attr("class", "col-sm-12");
            $("#colyou").hide();
            $(".tools").hide();
            chss++;
        } else {
            $("#colzuo").attr("class", "col-sm-9");
            $("#colyou").show();
            $(".tools").show();
            chss = 0;
        }
    });
    setup_draggable();

    $("#pop_page").on("click", function () {
        var $copy = $(".form-body").clone().appendTo(document.body);
        $copy.find(".tools, :hidden").remove();
        $.each(["draggable", "droppable", "sortable", "dropped", "ui-sortable", "ui-draggable", "ui-droppable", "form-body"], function (i, c) {
            $copy.find("." + c).removeClass(c).removeAttr("style")
        });
        var paras = document.body.getElementsByClassName('tools col-sm-3');
        for (i = 0; i < paras.length; i++) {
            paras[i].parentNode.removeChild(paras[i])
        }
        $copy.remove();
        var ojson = {
            server: [],
            host: [],
            aisle: [],
            route: [],
            signal: [],
            line: [],
        }
        //服务器
        $("#main .server").each(function (idx, elem) {
            var $elem = $(elem);
            var param = {
                id: $elem.data('id'),
                divId: $elem.attr('id'),
                name: $elem[0].innerText,
                positionX: parseInt($elem.css("left"), 10),
                positionY: parseInt($elem.css("top"), 10),
                type: $elem.data('type')
            }
            ojson.server.push(param)
        });

        //主机
        $("#main .host").each(function (idx, elem) {
            var $elem = $(elem);
            var param = {
                id: $elem.data('id'),
                divId: $elem.attr('id'),
                name: $elem[0].innerText,
                positionX: parseInt($elem.css("left"), 10),
                positionY: parseInt($elem.css("top"), 10),
                type: $elem.data('type')
            }
            ojson.host.push(param)
        });

        //通道
        $("#main .aisle").each(function (idx, elem) {
            var $elem = $(elem);
            var param = {
                id: $elem.data('id'),
                divId: $elem.attr('id'),
                name: $elem[0].innerText,
                positionX: parseInt($elem.css("left"), 10),
                positionY: parseInt($elem.css("top"), 10),
                type: $elem.data('type')
            }
            ojson.aisle.push(param)
        });

        //路由
        $("#main .route").each(function (idx, elem) {
            var $elem = $(elem);
            var param = {
                id: $elem.data('id'),
                divId: $elem.attr('id'),
                name: $elem[0].innerText,
                positionX: parseInt($elem.css("left"), 10),
                positionY: parseInt($elem.css("top"), 10),
                type: $elem.data('type')
            }
            ojson.route.push(param)
        });

        //信号
        $("#main .signal").each(function (idx, elem) {
            var $elem = $(elem);
            var param = {
                id: $elem.data('id'),
                divId: $elem.attr('id'),
                name: $elem[0].innerText,
                positionX: parseInt($elem.css("left"), 10),
                positionY: parseInt($elem.css("top"), 10),
                type: $elem.data('type')
            }
            ojson.signal.push(param)
        });
        //连线
        $.each(jsPlumb.getConnections(), function (idx, connection) {
            var param = {
                connectionId: connection.id,
                pageSourceId: connection.sourceId,
                pageTargetId: connection.targetId
            }
            ojson.line.push(param)
        });
        //打印json
        if (ojson.line.length === 0) {
            alert("审批流程创建失败！");
            return false
        }
        var process_code = JSON.stringify(ojson)                 // 流程代码
        if (!process_code) {
            alert("请创建流程！");
            return false
        }
        var current_page_url = window.location.href;
        var id = current_page_url.split("=")[1]
        var flow_html = document.getElementById("deviceRight").innerHTML            // 流程代码
        var xhr = new XMLHttpRequest()
        var local_host = window.location.host;          // 获取当前IP
        xhr.open('post', "/personal-center/product_update_view", true);
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
        xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
        xhr.send("id="+id+"&process_json=" + String(process_code) + "&process_html=" + String(flow_html))
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    var JsonDate = JSON.parse(xhr.responseText);
                    if (JsonDate['code'] === 200) {
                        if(JsonDate['message']==='success'){
                            // alert('修改成功！！')
                        }
                        alert(JsonDate['message'])
                        window.parent.location.reload()
                    } else {
                        alert(JsonDate['message'])
                        window.location.reload();
                    }
                }
            }
        }
    })
    //点击添加表单
    $(".btntext,.btntexts").click(function () {
        $(tableList($(this).attr("id"))).appendTo($(".ui-sortable"));
        $(".labcheck input").unbind('click');
        $(".labcheck input").click(function () {
            if ($(this).is(":checked")) {
                alert("选中");
            } else {
                alert("未选中");
            }
        });
        //时间初始化
        $(".form_datetime").datetimepicker({
            language: 'zh-CN', //日期
            format: "yyyy/mm/dd hh:ii",
            initialDate: new Date(), //初始化当前日期
            autoclose: true, //选中自动关闭
            todayBtn: true //显示今日按钮
        });
        //上传初始化
        $('.uploadfile').fileinput({
            language: 'zh'
        });
    });
});

var setup_draggable = function () {
    $(".draggable").draggable({
        appendTo: "body",
        helper: "clone"
    });
    $(".droppable").droppable({
        accept: ".draggable",
        helper: "clone",
        hoverClass: "droppable-active",
        drop: function (event, ui) {
            $(".empty-form").remove();
            var $orig = $(ui.draggable);
            if (!$(ui.draggable).hasClass("dropped")) {
                $(tableList($orig.attr("id"))).appendTo(this);
                //时间初始化
                $(".form_datetime").datetimepicker({
                    language: 'zh-CN', //日期
                    format: "yyyy/mm/dd hh:ii",
                    initialDate: new Date(), //初始化当前日期
                    autoclose: true, //选中自动关闭
                    todayBtn: true //显示今日按钮
                });
                //上传初始化
                $('.uploadfile').fileinput({
                    language: 'zh'
                });
            } else {
                if ($(this)[0] != $orig.parent()[0]) {
                    var $el = $orig.clone().appendTo(this);
                    $orig.remove()
                }
            }
        }
    }).sortable()
};
